package permsauth

import (
	"a-common/constant"
	"a-common/core/redis"
	"a-system/domain/entity"
	"log/slog"
)

// AuthPerms 权限认证
func AuthPerms(role *[]string, perms string) bool {
	if role == nil || len(*role) == 0 {
		return false
	}
	for _, r := range *role {
		// 从缓存中获取权限信息
		ok, err := redis.New().SIsMember(constant.LOGIN_ROLE+r, perms)
		if err != nil && ok {
			slog.Error(err.Error())
		}
		if err == nil && ok {
			return true
		}
	}
	return false
}

type MStruct struct {
	MenuId int64
	Perms  string
}
type RStruct struct {
	RoleId  int64
	RoleKey string
	Menus   []MStruct
}

// UploadCache 刷新权限缓存
func UploadCache(allRoleMenu []*entity.SysRoleMenuVo) error {
	// 获取数据库权限菜单
	// allRoleMenu, err := dao.NewSysRoleDao().GetAllRoleMenu()
	// if err != nil {
	// 	return err
	// }
	var rm []RStruct
	// 缓存菜单
	for _, arr := range allRoleMenu {
		rhas := false
		for index, r := range rm {
			if r.RoleId == arr.RoleId {
				rhas = true
				// 拼接
				mhas := false
				for _, m := range r.Menus {
					if m.MenuId == arr.MenuId {
						mhas = true
						break
					}
				}
				if !mhas && arr.Perms != "" {
					var m MStruct
					m.MenuId = arr.MenuId
					m.Perms = arr.Perms
					r.Menus = append(r.Menus, m)
					rm[index] = r
				}
				break
			}
		}
		if !rhas && arr.RoleKey != "" {
			// 新增
			var r RStruct
			r.RoleId = arr.RoleId
			r.RoleKey = arr.RoleKey
			if arr.Perms != "" {
				var m MStruct
				m.MenuId = arr.MenuId
				m.Perms = arr.Perms
				r.Menus = append(r.Menus, m)
			}
			rm = append(rm, r)
		}
	}

	rCil := redis.New()
	for _, r := range rm {
		// 删除旧缓存
		err := rCil.Del(constant.LOGIN_ROLE + r.RoleKey)
		if err != nil {
			return err
		}
		// 缓存菜单权限
		mList := make([]any, len(r.Menus))
		for i, val := range r.Menus {
			mList[i] = val.Perms
		}
		// 设置缓存
		err = redis.New().SAdd(constant.LOGIN_ROLE+r.RoleKey, mList)
		if err != nil {
			return err
		}

	}
	return nil
}
